<?php
error_reporting(E_ALL);

include_once 'common_classes.php';
include_once 'config.php';
include_once 'results_grid.php';

// set our user info with our answers
$userinfo = new UserInformation();
$userinfo->setAnswers($_POST);

// the class that brings it all together
$resultgrid = new ResultsGrid();

// add the questions to the grid
$questions = QueryBuilder::getAllQuestionsForCurrentElection();
$qcount = count($questions[0]); //QueryBuilder::getCountOfQuestionsForCurrentElection();

// add user to grid ranking
// turn him into a candidate first, its easier
$usercandidate = new CandidateInformation();
$usercandidate->setName("Your answers");
$usercandidate->setAnswers($userinfo->getAnswers());
$max = ($qcount * 2) + (Config::number_of_important_questions * 2);
$resultgrid->addRanking($usercandidate, $max);


for($i = 0; $i < $qcount; $i++) {
	$name = $questions[0][$i];
	$id = $questions[1][$i];
	$resultgrid->addQuestion($name, $id);
	
	// add user answers to the grid
	$resultgrid->addScore($id, $usercandidate->getName(), $userinfo->getAnswer($id), 2, 0, "");
}

// get the candidate details from the database
$candidates = QueryBuilder::getAllCandidateDetailsForCurrentElection();

// add the candidates to the grid
$ccount = count($candidates);
for($i = 0; $i < $ccount; $i++) {
	$answers = QueryBuilder::getAllAnswersForCandidateID($candidates[$i][0]);

	// if this candidate has filled in any answers
	if(count($answers) > 0) {
		$candidate = new CandidateInformation();
		$candidate->setID($candidates[$i][0]);
		$candidate->setName($candidates[$i][1]);
		$candidate->setUserID($candidates[$i][2]);
		$candidate->setRealName($candidates[$i][3]);
		$candidate->setDescription($candidates[$i][4]);
		$candidate->setURL($candidates[$i][5]);
		$candidate->setCorp($candidates[$i][6]);
		$candidate->setAlliance($candidates[$i][7]);
		$candidate->setAnswers($answers);

		// get our total score
		$total = $userinfo->compareWithCandidate($candidate);

		//echo $candidate->getName() . ' ' . $total . '<br />';

		// add to the grid
		$resultgrid->addRanking($candidate, $total);

		// for each question, add the score of this candidate to the grid
		for($j = 0; $j < $qcount; $j++) {
			$question = $questions[0][$j];
			$id = $questions[1][$j];
			$score = $candidate->getScore($id);
			$answer = $candidate->getAnswer($id);
			$isImportant = $candidate->isImportant($id);
			$explanation = $candidate->getExplanation($id);
			$resultgrid->addScore($id, $candidate->getName(), $answer, $score, $isImportant, $explanation);
		}
	}
}

session_start();

$_SESSION['grid'] = serialize($resultgrid);

header('location:step_3_view.php');
?>